package com.enzoism.springboot.dive.bis.datastruct;

/**
 * 内部类使用
 * 1）可以将迭代的接口提取出来
 * 2）然后每个类自己去实现自己的迭代
 * 3）保障迭代安全，不会被其他外部资源调用
 */
public class MySequence {
    private Object[] items;
    private int next = 0;

    // 初始化时，创建数组的尺寸为传入的size
    public MySequence(int size) {
        items = new Object[size];
    }

    public static void main(String[] args) {
        // 添加数据到数组
        int size = 10;
        MySequence mySequence = new MySequence(size);
        for (int i = 0; i < size; i++) {
            mySequence.add("小明" + i);
        }

        // 进行数据对象迭代
        MySelector selector = mySequence.selector();
        while (!selector.end()) {
            System.out.println(selector.current());
            selector.next();
        }
    }

    // 添加元素到数组的尾部
    public void add(Object x) {
        if (next < items.length) {
            items[next++] = x;
        }
    }

    // 内部类暴露
    public MySelector selector() {
        return new MySelectorImpl();
    }

    // 自定义一个迭代器接口
    public interface MySelector {
        boolean end();

        Object current();

        void next();
    }

    // 内部类直接共享外部类的变量
    public class MySelectorImpl implements MySelector {
        private int i = 0;

        @Override
        public boolean end() {
            return i == items.length;
        }

        @Override
        public Object current() {
            return items[i];
        }

        @Override
        public void next() {
            if (i < items.length) {
                i++;
            }
        }
    }


}
